import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { In, Repository } from 'typeorm'
import { Menu } from '../menu/entities/menu.entity'
import { Role } from '../role/entities/role.entity'
import { CreateAuthDto } from './dto/create-auth.dto'
import { UpdateAuthDto } from './dto/update-auth.dto'
import { Auth } from './entities/auth.entity'
import { treeMenu } from './utils'

@Injectable()
export class AuthService {
  constructor(
    @InjectRepository(Auth) private readonly auth: Repository<Auth>,
    @InjectRepository(Role) private readonly role: Repository<Role>,
    @InjectRepository(Menu) private readonly menu: Repository<Menu>
  ) {}
  async create(createAuthDto: CreateAuthDto) {
    const auth = new Auth()
    const role = await this.role.findOne({
      where: { id: createAuthDto.roleId }
    })
    auth.role = role
    auth.menuId = createAuthDto.menuId
    return this.auth.save(auth)
  }

  async findAll(params: {
    page: number
    pageSize: number
    departmentId?: number
    isDelete?: boolean
  }) {
    return await this.auth.find({ relations: ['role'] })
  }

  async findAuthMenu(role: number) {
    const auth = await this.auth.findOne({
      relations: ['role'],
      where: { role: { id: role } }
    })
    const menu = await this.menu.find({
      relations: ['parent'],
      where: { id: In(auth.menuId.split(',')) }
    })
    const menuTree = treeMenu(menu)
    return menuTree
  }

  async findOne(id: number) {
    return await this.auth.find({ where: { id } })
  }

  update(id: number, updateAuthDto: UpdateAuthDto) {
    return this.auth.update(id, updateAuthDto)
  }

  remove(ids: number[]) {
    return this.auth.softDelete(ids)
  }

  thoroughRemove(ids: number[]) {
    return this.auth.delete(ids)
  }

  restore(ids: number[]) {
    return this.auth.restore(ids)
  }
}
